from django.http import JsonResponse
from django.shortcuts import render, redirect
from app01.models import TieZi, ReplyTieZi, ReplyArticle
from app01.models import Article
from app01.models import User_Article_Like, User_TieZi_Like, UserGameScore, UserNovelScore


# Create your views here.


def me(request):
    coo = request.session.get('info', "")
    if request.method == 'GET':
        return render(request, "me/me.html", {"coo": coo})


def me_fabu_article(request):
    coo = request.session.get('info', "")
    if request.method == 'GET':
        queryset = Article.objects.filter(user_id_id=coo["id"])
        return render(request, "me/me_fabu_article.html", {"queryset": queryset, "coo": coo})


def me_fabu_tiezi(request):
    coo = request.session.get('info', "")
    if request.method == 'GET':
        queryset = TieZi.objects.filter(user_id_id=coo["id"])
        return render(request, "me/me_fabu_tiezi.html", {"queryset": queryset, "coo": coo})


def me_pl(request):
    coo = request.session.get('info', "")
    if request.method == 'GET':
        queryset = ReplyArticle.objects.filter(user_id_id=coo["id"])
        return render(request, "me/me_pl.html", {"queryset": queryset, "coo": coo})


def me_like(request):
    coo = request.session.get('info', "")
    if request.method == 'GET':
        queryset1 = User_Article_Like.objects.filter(user_id_id=coo["id"])
        queryset2 = User_TieZi_Like.objects.filter(user_id_id=coo["id"])
        queryset = queryset1.union(queryset2)
        print(type(queryset1))
        return render(request, "me/me_Like.html", {"queryset": queryset, "coo": coo})


def me_like_delete(request):
    uid = request.GET.get('uid')
    exists = User_Article_Like.objects.filter(id=uid).exists()
    if not exists:
        return JsonResponse({"status": False, 'error': "删除失败，数据不存在。"})

    row_object = User_Article_Like.objects.filter(id=uid).first()
    likes = Article.objects.filter(id=row_object.like_id_id).first().likes - 1
    Article.objects.filter(id=row_object.like_id_id).update(likes=likes)
    User_Article_Like.objects.filter(id=uid).delete()
    return JsonResponse({"status": True})


def me_pl_delete(request):
    uid = request.GET.get('uid')
    exists = ReplyArticle.objects.filter(id=uid).exists()
    if not exists:
        return JsonResponse({"status": False, 'error': "删除失败，数据不存在。"})

    row_object = ReplyArticle.objects.filter(id=uid).first()
    comments = Article.objects.filter(id=row_object.article_id_id).first().comments - 1
    Article.objects.filter(id=row_object.article_id_id).update(comments=comments)
    ReplyArticle.objects.filter(id=uid).delete()
    return JsonResponse({"status": True})
